#include "HTTPServer.h"
#include "StringUtil.h"
#include "HTTPHandlerTask.h"

SK

HTTPServer::HTTPServer (const String& rootDir, u16 localPort)
: 
localOnly (false),
lport (localPort),
root(rootDir)
{
}

HTTPServer::HTTPServer (const String& rootDir, const HTTPServerOptions &options)
: 
lport (options.localPort),
localOnly (options.localHostOnly),
root(rootDir)
{
}

HTTPServer::~HTTPServer ()
{
}

void HTTPServer::addThread (Thread *t)
{
    ScopedLock s (&threadLock);
    threads.push_back (t);
}

void HTTPServer::removeThread (Thread *t)
{
    ScopedLock s (&threadLock);
    threads.remove (t);
    delete t;
}


void HTTPServer::start (void)
{
    mainSoc = new Socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);

    if (localOnly)
        mainSoc->bind ("127.0.0.1",this->lport);
    else
        mainSoc->bind (this->lport);

    mainSoc->listen (10);

    while (true)
    {
        curClient = mainSoc->accept ();
        Thread *t = new Thread (NULL);
        HTTPHandlerTask *tsk = new HTTPHandlerTask (this, t,curClient, root);
        addThread (t);
        t->start (tsk);
    }
}

void HTTPServer::_onRequestComplete (Thread *t)
{
    this->removeThread (t);
}

EK